package com.nondo.rdp.auth.service.impl;

import com.nondo.rdp.auth.common.UserUtils;
import com.nondo.rdp.auth.domain.Role;
import com.nondo.rdp.auth.domain.User;
import com.nondo.rdp.auth.endpoint.model.Page;
import com.nondo.rdp.auth.repository.RoleRepository;
import com.nondo.rdp.auth.service.RoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 岗位服务接口实现
 * com.seelyn.superp.core.service.impl
 *
 * @author linfeng
 * @since 2017/7/30
 */
@Service
@Transactional(readOnly = true)
public class RoleServiceImpl extends BaseService<Role> implements RoleService {

    @Autowired
    private RoleRepository roleRepository;

    @Override
    public Role findOne(Long id) {
        return roleRepository.findOne(id);
    }

    @Override
    public Page<Role> find(final Page<Role> page, final Role company) {

        Sort sort = new Sort(Sort.Direction.ASC, "name");
        PageRequest pageRequest = new PageRequest(page.getPageNumber(), page.getPageSize(), sort);
        org.springframework.data.domain.Page<Role> dictPage = roleRepository.findAll((root, query, builder) -> {

            List<Predicate> predicates = new ArrayList<>();
            if (company != null) {
                if (StringUtils.isNotEmpty(company.getName())) {
                    predicates.add(builder.like(root.get("name"), "%" + company.getName() + "%"));
                }
                if (StringUtils.isNotEmpty(company.getEnname())) {
                    predicates.add(builder.like(root.get("enname"), "%" + company.getEnname() + "%"));
                }
            }
            predicates.add(builder.like(root.get("delFlag"), Role.DEL_FLAG_NORMAL));
            Predicate[] predicatesArray = new Predicate[predicates.size()];
            predicates.toArray(predicatesArray);
            return builder.and(predicatesArray);

        }, pageRequest);
        return new Page<>(dictPage);
    }

    @Transactional()
    @Override
    public void save(Role role) {
        roleRepository.save(role);
    }

    @Transactional()
    @Override
    public void delete(Long id) {
        roleRepository.deleteById(id);
    }

    @Override
    public Role findPositionByName(String name) {
        return roleRepository.findByName(name);
    }

    @Override
    public Role findPositionByEnName(String enname) {
        return roleRepository.findByEnnameEquals(enname);
    }

    @Override
    public List<Role> findAll() {
        return roleRepository.findAll();
    }

}
